<!-- 可以直接传入data,也可以传入api请求数据 -->
<template>
  <div class="custom-tree" :style="{ width: width }">
    <div class="tree-title">
      <span>
        <i class="iconfont icon-daohang1"></i>
        {{ title }}
      </span>
      <i class="iconfont icon-shuaxin" @click="refresh"></i>
    </div>
    <el-scrollbar>
      <el-tree
        ref="treeRef"
        :show-checkbox="showCheckbox"
        v-loading="loading"
        v-if="treeData.length > 0"
        class="unit-tree"
        :style="{ 'max-width': width, width: width }"
        :node-key="nodeKey"
        :data="treeData"
        :props="treeProps"
        :current-node-key="currentNodeKey"
        :default-expanded-keys="defaultExpandedKeys"
        :default-checked-keys="defaultCheckedKeys"
        :check-on-click-node="checkOnClickNode"
        @node-click="onNodeClick"
        @check="onCheck"
        auto-expand-parent
      >
        <template #default="{ node, data }">
          <slot name="node" :node="node" :data="data">
            <el-tooltip class="box-item" effect="dark" :content="node.label" placement="top-start" :disabled="node.label.length < 9">
              <span class="tree-node">{{ node.label.length > 9 ? node.label.slice(0, 8) + '...' : node.label }}</span>
            </el-tooltip>
          </slot>
        </template>
      </el-tree>
    </el-scrollbar>
    <!-- <CustomEmpty :style="{ height: 'calc( 100% - 70rem)' }" v-else></CustomEmpty> -->
  </div>
</template>

<script setup>
import { ref, onBeforeMount, onMounted, computed, watch, onBeforeUnmount, nextTick } from 'vue'
import { http } from '@/utils/index.js'
import { stores } from '@/stores/index.js'
const dynamicParamsStore = stores.useDynamicParamsStore()
const currentNodeKey = defineModel('currentNodeKey', { default: '' }) //和selectFirstNode 互相排斥
const defaultCheckedKeys = defineModel('defaultCheckedKeys', { default: [] })
const defaultExpandedKeys = defineModel('defaultExpandedKeys', { default: [] })
const props = defineProps({
  width: {
    type: String,
    default: '200rem'
  },
  title: {
    type: String,
    default: '请选择单位'
  },
  data: {
    type: Array,
    default: () => {
      return []
    }
  },
  api: {
    type: String,
    default: '/znjszd3/comm/tree/getDwdmTree'
  },

  method: {
    type: String,
    default: 'get'
  },
  showCheckbox: {
    type: Boolean,
    default: false
  },
  checkOnClickNode: {
    type: Boolean,
    default: false
  },
  treeProps: {
    type: Object,
    default: () => {
      return {
        children: 'children',
        label: 'zdzw'
      }
    }
  },
  params: {
    type: Object,
    default: () => {
      return {}
    }
  },
  nodeKey: {
    type: String,
    default: 'zddm'
  },
  selectFirstNode: {
    //是否默认选中第一个node ，和 currentNodeKey 互相排斥
    type: Boolean,
    default: false
  },

  // defaultExpandedKeys: {
  //   type: Array,
  //   default: () => {
  //     return []
  //   }
  // },
  defaultCheckedKeys: {
    type: Array,
    default: () => {
      return []
    }
  },
  currentNodeKey: {
    type: [String, Number],
    default: ''
  }
})
const emit = defineEmits(['leaf-node-click', 'node-click', 'check'])

const treeRef = ref()
const loading = ref(false)

const treeData = ref(props.data)
watch(
  treeData,
  (newVal) => {
    if (newVal.length > 0) {
      nextTick(() => {
        if (props.selectFirstNode) {
          getFirstNode(newVal)
        }
        if (currentNodeKey.value) {
          treeRef.value.setCurrentKey(currentNodeKey.value, true)
        }
      })
    }
  },
  {
    once: true
  }
)

onBeforeUnmount(() => {
  dynamicParamsStore.delDynamicParams('treeNode')
  currentNodeKey.value = ''
  defaultCheckedKeys.value = []
  defaultExpandedKeys.value = []
})
onMounted(() => {
  if (props.data.length == 0 && props.api != '') {
    getData()
  }
})
const getData = () => {
  loading.value = true
  http(props.api, props.method, props.params)
    .then((res) => {
      treeData.value = res.data
    })
    .finally(() => {
      loading.value = false
    })
}
//获取tree第一个节点的数据,并选中改节点
const getFirstNode = (arr) => {
  if (arr[0].children) {
    getFirstNode(arr[0].children)
  } else {
    treeRef.value.setCurrentKey(arr[0][props.nodeKey], true)
    emit('leaf-node-click', arr[0])
    dynamicParamsStore.setDynamicParams('treeNode', arr[0])
  }
}
const onNodeClick = (nodeObj, node, TreeNode, event) => {
  emit('node-click', nodeObj, node, TreeNode, event)
  //点击的是叶子节点
  if (node.isLeaf) {
    //没有被禁止选中
    if (!node.disabled) {
      dynamicParamsStore.setDynamicParams('treeNode', node.data)
      emit('leaf-node-click', node.data)
    }
  }
}
const onCheck = (node, checked) => {
  emit('check', node, checked)
}
const refresh = () => {
  if (props.api) {
    getData()
  }
}

defineExpose({
  treeRef,
  getData
})
</script>
<style lang="scss" scoped>
.custom-tree {
  // padding: 5px;
  height: 100%;

  background: #fff;

  .tree-title {
    margin-bottom: 10px;
    height: 50px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 16px;
    padding: 20px 12px;
    border-bottom: 1px solid #eee;
    .icon-daohang1 {
      margin-right: 5px;
      font-size: 16px;
      font-weight: 600;
    }
    .icon-shuaxin {
      cursor: pointer;
    }
  }
  ::v-deep(.el-scrollbar) {
    height: calc(100% - 70px);
  }
  ::v-deep(.el-tree) {
    // border: 1px solid red;
    height: calc(100% - 70px);
    // overflow: auto;

    .el-tree-node__content {
      height: 40px;
    }
    .el-tree-node__label {
      font-size: 15px;
    }

    .el-tree-node.is-current:not(.is-expanded) {
      background-color: #f5f7fa;
      // background-color: #ebebeb;
    }
    .tree-node {
      font-size: 15px;
    }
  }
}
</style>
